package com.woniuxy.util;

import com.woniuxy.exception.CustomException;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class MinioUtil {

    private final MinioClient minioClient;

//    @Value("${minio.bucket-name}")
//    private String bucketName;
    @Value("${minio.endpoint}")
    private String endpoint;

    public MinioUtil(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    // 上传文件
    public String uploadFile(MultipartFile file, String bucketName) throws Exception {
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            throw new CustomException(ResponseCode.MINIO_ERROR, "上传文件为空");
        }
        // 判断存储桶是否存在
        createBucket(bucketName);
        // 文件名
        String originalFilename = file.getOriginalFilename();
        // 新的文件名 = 存储桶名称_时间戳.后缀名
        String fileName = bucketName + "_" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 开始上传
        InputStream inputStream = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(inputStream, inputStream.available(), -1).build();
        minioClient.putObject(args); //上传服务中
        String imgPath = endpoint + "/" + bucketName + "/" + fileName;
        return imgPath;
    }

    // 创建桶
    public void createBucket(String bucketName) throws Exception {
        // 检查桶是否已经存在
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        boolean bucketExists = minioClient.bucketExists(bucketExistsArgs);
        if (!bucketExists) {
            minioClient.makeBucket(
                    MakeBucketArgs.builder()
                            .bucket(bucketName)
                            .build()
            );
        } else {
            throw new CustomException(ResponseCode.MINIO_ERROR, "Bucket already exists");
        }
    }

    // 下载文件
//    public InputStream downloadFile(String fileName) throws Exception {
//        return minioClient.getObject(
//                GetObjectArgs.builder()
//                        .bucket(bucketName)
//                        .object(fileName)
//                        .build()
//        );
//    }
}
